package com.idroc.coelacanth.core.message;

import java.util.concurrent.Executor;

import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import org.jboss.netty.handler.logging.LoggingHandler;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Slf4JLoggerFactory;

public class MessageFactory implements ChannelPipelineFactory {

	/**
	 * 消息字节流帧解码器
	 */
	private ChannelHandler frameDecoder = new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4);
	
	/**
	 * 消息字节流编码器
	 */
	private ChannelHandler frameEncoder = new LengthFieldPrepender(4);
	
	/**
	 * 消息解码器
	 */
	private ChannelHandler messageDecoder = new MessageDecoder();
	
	/**
	 * 消息编码器
	 */
	private ChannelHandler messageEncoder = new MessageEncoder();
	 
	/**
	 * 消息分发的字节流处理器
	 */
	private MessageDispatchHandler messageDispatchHandler = new MessageDispatchHandler();		

	public ChannelPipeline getPipeline() throws Exception {

		ChannelPipeline cp = Channels.pipeline();
		return addMessageHandlersTo(cp);
	}
	
	/**
	 * 给ChannelPipeline对象增加消息协议的字节流处理器集合
	 * @param cp
	 * @return
	 */
	public ChannelPipeline addMessageHandlersTo(ChannelPipeline cp) {
		
		InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
		cp.addLast("logging", new LoggingHandler());
		
		cp.addLast("frameDecoder", frameDecoder);
		cp.addLast("frameEncoder", frameEncoder);
		
		cp.addLast("messageDecoder", messageDecoder);
		cp.addLast("messageEncoder", messageEncoder);
		
		//Executor ox = new OrderedMemoryAwareThreadPoolExecutor(16, 1048576, 1048576);
		//ExecutionHandler executionHandler = new ExecutionHandler(ox);
		//cp.addLast("executionHandler", executionHandler);
		
		cp.addLast("messageDispatchHandler", messageDispatchHandler);
		
		return cp;
	}
	
	/**
	 * 消息分发的字节流处理器
	 * @return -- 消息分发的字节流处理器
	 */
	public MessageDispatchHandler getMessageDispatcher() {
		
		return messageDispatchHandler;
	}
}
